<?php
declare(strict_types=1);

namespace think\admin\test\service;

use think\admin\Service;
use think\admin\test\repository\UserRepository;
use think\admin\exception\BusinessException;

class UserService extends Service
{
    /**
     * 初始化
     */
    protected function initialize(): void
    {
        $this->repository = new UserRepository();
    }

    /**
     * 用户登录
     * @param array $data
     * @return array
     * @throws BusinessException
     */
    public function login(array $data): array
    {
        try {
            /** @var UserRepository $repository */
            $repository = $this->repository;
            $user = $repository->findByUsername($data['username']);

            if (!$user->verifyPassword($data['password'])) {
                throw new BusinessException('密码错误');
            }

            if ($user->status != 1) {
                throw new BusinessException('账号已被禁用');
            }

            // 获取用户角色
            $roles = $repository->getUserRoles($user->id);

            // 生成登录令牌
            $token = $this->createToken($user->id);

            return [
                'user' => $user->toArray(),
                'roles' => $roles,
                'token' => $token
            ];
        } catch (BusinessException $e) {
            throw new BusinessException('用户不存在');
        }
    }

    /**
     * 用户注册
     * @param array $data
     * @return bool
     * @throws Exception
     */
    public function register(array $data): bool
    {
        /** @var UserRepository $repository */
        $repository = $this->repository;

        // 检查用户名是否存在
        if ($repository->isUsernameExists($data['username'])) {
            throw new BusinessException('用户名已存在');
        }

        // 检查邮箱是否存在
        if ($repository->isEmailExists($data['email'])) {
            throw new BusinessException('邮箱已存在');
        }

        // 创建用户
        return $this->transaction(function () use ($repository, $data) {
            // 创建用户
            $result = $repository->create($data);
            if (!$result) {
                return false;
            }

            // 分配默认角色
            return $repository->assignRoles($repository->model->id, [1]); // 假设 1 是默认用户角色ID
        });
    }

    /**
     * 分配角色
     * @param int $userId
     * @param array $roleIds
     * @return bool
     */
    public function assignRoles(int $userId, array $roleIds): bool
    {
        /** @var UserRepository $repository */
        $repository = $this->repository;
        return $repository->assignRoles($userId, $roleIds);
    }

    /**
     * 创建登录令牌
     * @param int $userId
     * @return string
     */
    protected function createToken(int $userId): string
    {
        // 这里应该使用 JWT 或其他令牌生成方式
        // 这里只是示例，实际应用中应该使用更安全的方式
        return md5($userId . time() . uniqid());
    }
} 